﻿using MQTTnet;
using MQTTnet.Protocol;
using MQTTnet.Server;

namespace SiriWeb
{
    public class MqttWorker : IHostedService
    {
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            var option = new MqttServerOptionsBuilder().WithDefaultEndpoint().Build();

            App.MqttServer = new MqttFactory().CreateMqttServer(option);
            App.MqttServer.ValidatingConnectionAsync += _mqttServer_ValidatingConnectionAsync;
            await App.MqttServer.StartAsync();
            await Console.Out.WriteLineAsync("Server Start");
        }

        private Task _mqttServer_ValidatingConnectionAsync(ValidatingConnectionEventArgs e)
        {
            //必须是32位去掉-的GUID
            if (e.ClientId.Length != 32)
            {
                e.ReasonCode = MqttConnectReasonCode.ClientIdentifierNotValid;
            }

            if (e.UserName != "anonymous")
            {
                e.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
            }

            if (e.Password != "anonymous")
            {
                e.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
            }
            return Task.CompletedTask;
        }

        public async Task StopAsync(CancellationToken cancellationToken)
        {
            foreach (var clientStatus in App.MqttServer.GetClientsAsync().Result)
            {
                await clientStatus.DisconnectAsync();
            }
            await App.MqttServer.StopAsync();
            App.MqttServer = null;
        }
    }
}
